﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;


namespace Pibby.Core.Feeds
{
	public class XmlSanitizer
	{
		struct ReplaceText
		{
			public string oldString;
			public string newString;

			public ReplaceText(string o, string n)
			{
				this.oldString = o;
				this.newString = n;
			}
		}

		private List<ReplaceText> TextReplacement = new List<ReplaceText>();

		public XmlSanitizer()
		{
			this.LoadDefaults();
		}

		private void LoadDefaults()
		{
            this.TextReplacement.Add(new ReplaceText(@"ï»¿", ""));
            this.TextReplacement.Add(new ReplaceText("&lt;", ""));
            this.TextReplacement.Add(new ReplaceText("&gt;", ""));
            this.TextReplacement.Add(new ReplaceText("br/", ""));
			this.TextReplacement.Add(new ReplaceText("<itunes:block>no</itunes:block>", ""));
		}
		
		public string Clean(string toClean)
		{
			if (string.IsNullOrEmpty(toClean))
				return string.Empty;

			var builder = new StringBuilder(toClean);

			foreach (XmlSanitizer.ReplaceText r in this.TextReplacement)
			{
				builder.Replace(r.oldString, r.newString);
			}

			return builder.ToString();
		}

		public static string StripHtml(string html)
		{
		    if (string.IsNullOrEmpty(html))
		        return string.Empty;

		    // Remove all <open> and </close> tags.
		    var text = new StringBuilder(Regex.Replace(html, "<[^>]*>", String.Empty));

            const string NonBreakingSpace = "&nbsp;";
            const string Ampersand = "&amp;";
            const string TwoSpaces = "  ";
		    const string OneSpace = " ";

            text.Replace(NonBreakingSpace, OneSpace);
            text.Replace(Ampersand, "&");
		    text.Replace(TwoSpaces, OneSpace);
		    text.Replace("\t", OneSpace);
		    text.Replace("\n", OneSpace);

		    return text.ToString().Trim();
		}
	}    

}
